package yxy.game.pm2.command.wuchao;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.currency.Currencies;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.WuchaoMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.wuchao.WuchaoModule;
import yxy.game.pm2.module.wuchao.event.WuchaoEvent;
import yxy.game.pm2.module.wuchao.event.WuchaoEvent.EventType;

import java.util.ArrayList;
import java.util.List;

/** 乌巢 乌巢事件掉落 */
@MessageType(proto = Command.WuchaoEventDrop, classtype = WuchaoMessage.WuchaoEventDropRequest.class)
public class CMD_WuchaoEventDrop extends Command<WuchaoMessage.WuchaoEventDropRequest> {

	@Override
	public void execute(MessageSource messageSource, WuchaoMessage.WuchaoEventDropRequest request) {
		String playerCode = messageSource.getTag();
		List<String> eventCodeList = request.getCodeList();

		WuchaoMessage.WuchaoEventDropResponse.Builder response = WuchaoMessage.WuchaoEventDropResponse.newBuilder();

		WuchaoModule wuchaoModule = WuchaoModule.get(playerCode);
		if (wuchaoModule.getStage() <= 0) {
			send(messageSource, response, Result.WuchaoNotStart);// 没有开始挑战
			return;
		}
		try {
			if (wuchaoModule.tryLock()) {
				ArrayList<yxy.game.pm2.module.wuchao.event.WuchaoEventDrop> events = new ArrayList<>();
				for (String eventCode : eventCodeList) {
					WuchaoEvent event = wuchaoModule.getEvents().get(eventCode);

					if (event == null || event.isOver()) {
						send(messageSource, response, Result.WuchaoEventOver);// 事件不可用
						return;
					}
					if (!(event.getEventType().equals(EventType.Drop))) {
						send(messageSource, response, Result.ParamError);// 事件不可用
						return;
					}
					events.add((yxy.game.pm2.module.wuchao.event.WuchaoEventDrop) event);
				}

				Currencies rewards = new Currencies();
				for (yxy.game.pm2.module.wuchao.event.WuchaoEventDrop event : events) {
					rewards.add(event.getDrop());
					event.setOver(true);

					response.addCode(event.getCode());
				}
				wuchaoModule.set();

				new CurrencyHandle().addCurrency(playerCode, CCReason.乌巢之战, rewards);

				response.addAllReward(new CurrencyHandle().packItems(rewards));

				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			wuchaoModule.unlock();
		}
	}

	private void send(MessageSource messageSource, WuchaoMessage.WuchaoEventDropResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}